<?php
class lib
{
	const SETTING_AN_ARRAY = true;
	const NO_PERSISTENT_STORAGE = false;
	
	// 是否登陆
	public static function islogin()
	{
		return isset($_SESSION['user']);
	}
	
	public static function checkseccode($code)
	{
		return $code == lib::getitem('seccode', lib::NO_PERSISTENT_STORAGE);
	}
	
	// 获取对象
	public static function getitem($name, $persist = true)
	{
		$return = NULL;
		
		if(isset($_SESSION[$name])){
			$return = $_SESSION[$name];
			if (!$persist) unset($_SESSION[$name]);
		}
		
		return $return;
	}
	
	// 设置对象
	public static function setitem($name, $value, $is_array = false)
	{
		if($is_array){
			if(!isset($_SESSION[$name])){
				$_SESSION[$name] = array();
				$_SESSION[$name][] = $value;
			}
		}else{
			$_SESSION[$name] = $value;
		}
	}
	
	// 重定向
	public static function sendto($url = '')
	{
		if(empty($url)){
			$url = '/';
		}
		
		die(header('Location: ' . $url));
	}
	
	public static function seterror($error)
	{
		self::setitem('error', $error, self::SETTING_AN_ARRAY);
	}
	
	public static function setmessage($message)
	{
		self::setitem('message', $message, self::SETTING_AN_ARRAY);
	}
	
	public static function makehashedpassword(user $user=NULL, $password)
	{
		return MD5("i'mpicker".$password);
		//return sha1($user->username . $password);
	}
	
	public static function isuserexist($username){
		$user = new user(array('username'=>$username));
		return !is_null($user->username);
	}
	
	public static function checkusername($str){
		if(preg_match('/^[a-z][a-z0-9]{4,11}/', strtolower($str)))
			return strtolower(trim($str));
		else return false;
	}
	
	public static function checkemail($str){
		if(preg_match('/^(([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+([;.](([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+)*$/i', $str))
			return strtolower(trim($str));
		else return false;
	}
}